package com.miniotest.miniotest;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CreateFileSegment {
    public static void createFileSegment(String path){
        // 指定要生成的文件路径和名称
        String filePath = path; // 替换为你想保存文件的路径

        // 定义要生成的文件大小，这里为5MB，注意1MB = 1024 * 1024 字节
        long fileSize = 1024 * 1024 * 1024;

        try (FileOutputStream fos = new FileOutputStream(new File(filePath))) {
            // 创建一个byte数组用于写入数据
            byte[] buffer = new byte[1024]; // 缓冲区大小，可以根据实际情况调整

            // 填充buffer数组为随机数据或固定值（如0）
            // 这里我们简单地用0填充buffer
            for (int i = 0; i < buffer.length; i++) {
                buffer[i] = 0;
            }

            // 循环写入buffer，直到文件达到指定大小
            long writtenBytes = 0;
            while (writtenBytes < fileSize) {
                int toWrite = (int) Math.min(buffer.length, fileSize - writtenBytes);
                fos.write(buffer, 0, toWrite);
                writtenBytes += toWrite;
            }

            System.out.println("File " + filePath + " has been created successfully with size " + fileSize + " bytes.");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error occurred while creating the file.");
        }
    }
    static void init(CloseableHttpClient httpClient) throws IOException {
        HttpPost httpPost = new HttpPost("http://localhost:8080/file/init");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // md5
        String md5 = "12C345FF299595FF3C581BF5B229DE88";
        builder.addTextBody("md5",md5,ContentType.TEXT_PLAIN);
        // segNum
        String segNum = String.valueOf(256);
        builder.addTextBody("segNum",segNum,ContentType.TEXT_PLAIN);
        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);
        HttpResponse response = httpClient.execute(httpPost);
        System.out.println("response code:"+response.getStatusLine().getStatusCode()+" responseBody"+EntityUtils.toString(response.getEntity(), Consts.UTF_8));
    }
    static void upload(CloseableHttpClient httpClient,Integer segIndex) throws Exception {
        HttpPost httpPost = new HttpPost("http://localhost:8080/file/upload");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // multipartFile
        File file = new File("E:\\Develop\\test1.txt");
        builder.addBinaryBody("multipartFile", file, ContentType.DEFAULT_BINARY, file.getName());
        // md5
        String md5 = "12C345FF299595FF3C581BF5B229DE88";
        builder.addTextBody("md5",md5,ContentType.TEXT_PLAIN);
        // segCheck
        String segCheck = String.valueOf(1);
        builder.addTextBody("segCheck", segCheck, ContentType.TEXT_PLAIN);
        // segNum
        String segNum = String.valueOf(256);
        builder.addTextBody("segNum",segNum,ContentType.TEXT_PLAIN);
        // segIndex
        builder.addTextBody("segIndex",String.valueOf(segIndex),ContentType.TEXT_PLAIN);

        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);
        HttpResponse response = httpClient.execute(httpPost);
        System.out.println("response code:"+response.getStatusLine().getStatusCode()+" responseBody"+EntityUtils.toString(response.getEntity(), Consts.UTF_8));
    }
    static void done(CloseableHttpClient httpClient) throws IOException {
        HttpPost httpPost = new HttpPost("http://localhost:8080/file/done");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // md5
        String md5 = "12C345FF299595FF3C581BF5B229DE88";
        builder.addTextBody("md5",md5,ContentType.TEXT_PLAIN);
        // segNum
        String segNum = String.valueOf(256);
        builder.addTextBody("segNum",segNum,ContentType.TEXT_PLAIN);
        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);
        HttpResponse response = httpClient.execute(httpPost);
        System.out.println("response code:"+response.getStatusLine().getStatusCode()+" responseBody"+ EntityUtils.toString(response.getEntity(), Consts.UTF_8));
    }

    // 串行上传1G文本文件为53.126s
    // 并行上传1G文本文件为34.164s
    public static void main(String[] args) throws Exception {
        /*CloseableHttpClient httpClient = HttpClients.createDefault();
        long start = System.currentTimeMillis();
        init(httpClient);
        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        // 存储Future的列表，以便之后可以等待所有任务完成
        List<Future<?>> futures = new ArrayList<>();
        // 提交任务到线程池
        for (int i = 0; i < 256; i++) {
            int finalI = i;
            Future<?> future = executorService.submit(() -> {
                try {
                    upload(httpClient, finalI);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
            futures.add(future);
        }
        // 等待所有任务完成
        for (Future<?> future : futures) {
            future.get(); // 这会阻塞直到任务完成，或者抛出异常
        }

        done(httpClient);
        httpClient.close();
        long end = System.currentTimeMillis();
        System.out.println(end-start);*/
        createFileSegment("E:\\Develop\\test7.txt");
    }

}
